<template>
  <div class="pageheader">
    <el-page-header @back="$router.back()">
      <template #content>
        <span> {{ info.solution.name }} 方案指标 </span>
      </template>
    </el-page-header>
  </div>
  <el-card class="controlpanel" shadow="never">
    <!--         <el-button @click="saveBasicData" :disabled="step !== 0">校验并保存基本数据</el-button>
        <el-button @click="skipBasicData" :disabled="step !== 0">编辑其他信息</el-button>
        <el-button @click="toFirstStep" :disabled="step === 0">更改基本数据</el-button> -->
<!--    <el-button type="primary" @click="addIndicatorDialog">编辑指标</el-button>-->
    <el-button type="primary" @click="submit">提交数据</el-button>
  </el-card>
  <!--  <el-card class="controlpanel" shadow="never">-->
  <!--    指标号：<el-input class="w-50 m-2" style="width: 100px;margin-right: 20px" v-model="lineInput.mark"></el-input>-->
  <!--    数据：<el-input class="w-50 m-2" style="width: 300px;margin-right: 20px" placeholder="请输入数据，合计在最后" v-model="lineInput.value"></el-input>-->
  <!--    分隔符：<el-input class="w-50 m-2" style="width: 100px;margin-right: 20px"  v-model="lineInput.separator"></el-input>-->
  <!--    <el-button type="primary" @click="doLineInput">按行添加</el-button>-->
  <!--  </el-card>-->
  <el-tabs v-model="activeName" type="border-card" class="tabs">
    <el-tab-pane v-for="(table, index) in tables as any" :key="index" :label="table.tableName" :name="index"
      :disabled="step < index || (step !== 0 && index === 0)">
      <el-scrollbar>
        <table border="1" style="width: 100%">
          <th :colspan="50">{{ table.tableName }}表</th>
          <tr>
            <td style="width: 30px;text-align: left">序号</td>
            <td>项目</td>
            <td>单位</td>
            <template v-if="table.isArray === 0">
              <td>数据</td>
            </template>
            <template v-else>
              <td v-for="(year, index) in basicInfo.calcYear" :key="index">
                第{{ index + 1 }}年
              </td>
              <td>合计</td>
            </template>
          </tr>
          <template v-for="(item, index) in table.indicatorMarks" :key="index">
            <tr
              v-if="indicatorDict[item] !== undefined && indicatorDict[item].indicatorName !== '' && indicatorDict[item].indicatorName !== null">
              <template v-if="indicatorDict.hasOwnProperty(item)">
                <td style="text-align: left">
                  {{ table.viewMarks[index] }}
                </td>
                <td v-if="indicatorDict[item] !== undefined">{{ indicatorDict[item].indicatorName }}</td>
                <td>{{ indicatorDict[item].unit }}</td>
                <template v-if="table.isArray === 0">
                  <td v-if="indicatorDict[item].formula === 'OPTIONAL'">
                    <el-select v-model="dataSheet[item][0]" class="input-number" :size="inputNumberSize">
                      <el-option v-for="(opt, index) in indicatorDict[item].option" :key="index" :value="index"
                        :label="opt"></el-option>
                    </el-select>
                  </td>
                  <td v-else>
                    <el-input-number :disabled="indicatorDict[item].formula !== 'INPUT'" v-model="dataSheet[item][0]"
                      class="input-number" :size="inputNumberSize" controls-position="right"
                      placeholder="请输入"></el-input-number>
                  </td>
                </template>
                <template v-else>
                  <td v-for="(element, index) in dataSheet[item]" :key="index">
                    <el-input-number v-model="dataSheet[item][index]" :disabled="indicatorDict[item].formula !== 'INPUT'"
                      class="input-number" :size="inputNumberSize" controls-position="right" placeholder="请输入"
                      @change="change(item)"></el-input-number>
                  </td>
                </template>
                <!-- <td>{{ state.form.liquidFund.turnOverTime[0] }}</td> -->
              </template>
              <template v-else>
                <td style="text-align: left">
                  {{ table.viewMarks[index] }}
                </td>
                <td>{{ index }}</td>
                <template>
                  <td>
                    {{ item }}
                  </td>
                </template>
              </template>
            </tr>
          </template>

        </table>
      </el-scrollbar>
    </el-tab-pane>
  </el-tabs>
</template>
<script lang="ts" setup>
import { ref, reactive } from "vue";
import { ElMessage, formContextKey, TabsPaneContext } from "element-plus";
import solutionApi from "@/api/equipment/solution";
import dict from "@/api/equipment/dict";
import router from "@/router";
import { ElLoading } from "element-plus";
import { PROJECT_TYPE } from "@/NAPI";
import { request } from "@/api/REQ";

// 初始化项目基本信息

const routename = router.currentRoute.value.name;
const info = {
  project: { id: 0, name: "", type: 1, description: "", createTime: "" },
  solution: {} as any,
};
const proj = window.sessionStorage.getItem("project");
const solu = window.sessionStorage.getItem("solution");
console.log(solu);
if (proj !== null) {
  info.project = JSON.parse(proj);
} else {
  ElMessage.error("未获取到项目信息！");
}
if (solu === null) {
  ElMessage.error("未获取到方案信息！");
} else {
  info.solution = JSON.parse(solu);
}

// 表单

// tab索引
const activeName = ref(0);
// 步数
const step = ref(0);

// 页面基本信息
const basicInfo = reactive({
  calcYear: 1,
  consYear: 1,
  operYear: 0,
  transportationFangan: 0,
});
const lineInput = reactive({
  mark: "",
  value: "",
  separator: ""
})
const dataSheet = reactive({} as any); // 数据列表
const tables = ref([] as Array<any>);
const indicatorDict = ref({} as any);

// 获取指标表格
const getSheet = () => {
  dict.tables(info.solution.id).then((res) => {
    console.log(res);
    for (const i of res.data.data) {
      // if (i.tag === "IN") {
      tables.value.push(i);
      // }
    }
    createData();
    createArrays();
    getData();
    loadingInstance.close();
  });
  return;
};
// 获取指标对应的字典
const getIndicator = () => {
  dict.indicators(info.solution.id).then((res) => {
    indicatorDict.value = res.data.data;
    processIndicator();
  });
};
const processIndicator = () => {
  for (const key in indicatorDict.value) {
    if (indicatorDict.value[key].memo !== null)
      indicatorDict.value[key].option =
        indicatorDict.value[key].memo.split(" ");
  }
};

// 创建新数据模板
const createData = () => {
  for (const item of tables.value as any) {
    for (const mark of item.indicatorMarks) {
      dataSheet[mark] = [0];
    }
  }
};

// 获取数据模板
const getData = () => {
  solutionApi.solutionIndicators(info.solution.id).then((res) => {
    for (const key in res.data.data) {
      dataSheet[key] = res.data.data[key];
    }
    dataSheet["1.7"] = dataSheet["1.7"][0] != 0 ? dataSheet["1.7"] : [0.032];
    dataSheet["1.8"] = dataSheet["1.8"][0] != 0 ? dataSheet["1.8"] : [0.04];
    dataSheet["1.9"] = dataSheet["1.9"][0] != 0 ? dataSheet["1.9"] : [dataSheet["1"] == 1 ? 0.03 : 0.12];
    dataSheet["2.2"] = dataSheet["2.2"][0] != 0 ? dataSheet["2.2"] : [0.0388];
    dataSheet["2.4"] = dataSheet["2.4"][0] != 0 ? dataSheet["2.4"] : [0.03];
  });
};

// 根据计算期确定数组长度并初始化数组
const createArrays = () => {
  /* basicInfo.calcYear = dataSheet["1.1"][0];
  basicInfo.consYear = dataSheet["1.2"][0];
  basicInfo.operYear = dataSheet["1.3"][0]; */
  for (const key in dataSheet) {
    if (Object.prototype.hasOwnProperty.call(indicatorDict.value, key)) {
      if (indicatorDict.value[key].isArray === 1) {
        dataSheet[key] = new Array(31).fill(0);
      }
    }

  }

};

// 更新计算属性
const change = (item: any) => {
  // console.log(item);
  let sum = 0;
  const toProcess = dataSheet[item];
  for (let i = 0; i < basicInfo.calcYear; i++) {
    sum += toProcess[i];
  }
  toProcess[basicInfo.calcYear] = sum;
  // console.log(dataSheet);
};

// 提交
const submit = () => {
  console.log(dataSheet.value);
  solutionApi.updateIndicators(info.solution.id, dataSheet).then((res) => {
    if (res.data.code === 200) {
      ElMessage.success("操作成功");
    }
  });
};

//loading
let loadingInstance = ElLoading.service({});

// 添加指标dialog
const indicatorDialog = ref(false)
const indicatorAdd = reactive({
  solutionId: info.solution.id,
  indicatorMark: "",
  indicatorName: "",
})
const addIndicatorDialog = () => {
  indicatorDialog.value = true;
}
const clean = () => {
  indicatorDialog.value = false;
  indicatorAdd.solutionId = info.solution.id;
  indicatorAdd.indicatorMark = ""
  indicatorAdd.indicatorName = ""
}

getSheet();
getIndicator();


const basicInfoSaved = ref(false);
if (routename === "solution_edit") {
  basicInfoSaved.value = true;
}

const test = () => {
  console.log(dataSheet);
};
const inputNumberSize = "small" as "small" | "large";

const excelFile = ref();

// 上传excel模板
const addFile = (file: any, fileList: any) => {
  excelFile.value = file.raw;
  uploadTemplate()
};

// 删除excel模板
const removeFile = () => {
  excelFile.value = null
}

// 解析excel模板
const uploadTemplate = async () => {
  const headers = { 'Content-Type': 'multipart/form-data;charset=UTF-8' }
  const solution_id = info.solution.id
  const fullres = await request.post(`/import/${solution_id}`, excelFile, { headers })
  console.log(fullres)
  ElMessage.success("解析成功")
  getSheet();
  getIndicator();
}
</script>
<style lang="scss" scoped>
.controlpanel {
  margin: 20px;
}

.calbtn {
  margin: 20px;
  width: 300px;
}

.tabs>.el-tabs__content {
  width: 100%;
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.tabs {
  margin: 20px;
}

.basicInfoForm {
  width: 100%;

  .input {
    width: 300px;
  }

  td {
    .el-form-item {
      margin: 0;
      padding: 0;

      .el-form-item__content {
        margin: 0;
        text-align: center;
      }
    }
  }
}

/*表格样式*/
table {
  width: 100%;
  background: #ffffff;
  margin: 10px auto;
  border-collapse: collapse;
  border: 1px solid #dcdfe6;
  /*border-collapse:collapse合并内外边距
  (去除表格单元格默认的2个像素内外边距*/
}

th,
td {
  height: 25px;
  line-height: 25px;
  padding: 5px;
  text-align: center;
  border: 1px solid #dcdfe6;
  white-space: nowrap;
  border-collapse: collapse;
  -webkit-transition: all 0.5s, padding 0s;
  transition: all 0.5s, padding 0s;
}

th {
  font-weight: normal;
  border-collapse: collapse;
  background-color: #f0f2f5;
}

tr {
  background: #fff;
  -webkit-transition: all 0.5s, padding 0s;
  transition: all 0.5s, padding 0s;
  border-collapse: collapse;
  border: 1px solid #dcdfe6;
}

tr:hover {
  background: #ecf5ff;
}

td:hover {
  background-color: #d9ecff;
}
</style>
